const is = require('is-type-of');
module.exports = function (exportObj) {
  if (is.class(exportObj)) {
    return wrapControllerClass(exportObj);
  } else {
    return exportObj;
  }
};

/**
 * wrapControllerClass 包裹类方便后面用中间件
 * @param {Function} Controller 控制器类
 */
function wrapControllerClass(Controller) {
  let proto = Controller.prototype;
  const ret = {};

  // 遍历原型链
  while (proto !== Object.prototype) {
    const keys = Object.getOwnPropertyNames(proto);
    for (const key of keys) {
      // getOwnPropertyNames 将返回构造函数
      // 我们将忽略他
      if (key === 'constructor') {
        continue;
      }

      // 跳过getter, setter & non-function 属性properties
      const d = Object.getOwnPropertyDescriptor(proto, key);

      // 防止重写子方法prevent to override sub method
      if (typeof d.value === 'function' && !ret.hasOwnProperty(key)) {
        ret[key] = methodToMiddleware(Controller, key);
      }
    }
    proto = Object.getPrototypeOf(proto);
  }
  return ret;
}

function methodToMiddleware(Controller, key) {
  return (ctx, next) => {
    const controller = new Controller(ctx.context);
    return controller[key](ctx, next);
  };
}
